import axios from 'axios'
import type {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  AxiosRequestHeaders,
  InternalAxiosRequestConfig
} from 'axios'
import { ElMessage } from 'element-plus'

class Request {
  // axios 实例
  instance: AxiosInstance
  constructor(config?: AxiosRequestConfig) {
    this.instance = axios.create(config)
    this.instance.interceptors.request.use(
      (res: InternalAxiosRequestConfig) => {
        res.baseURL = import.meta.env.VITE_API_URL
        return res
      },
      (err: any) => err
    )
    this.instance.interceptors.response.use(
      // 因为我们接口的数据都在res.data下，所以我们直接返回res.data
      (res: AxiosResponse) => {
        if (res.status == 200) {
          return res.data
        } else {
          ElMessage.error(res.data.data.errMsg)
        }
        return res.data
      },
      (err: any) => err
    )
  }

  request(config: AxiosRequestConfig) {
    return this.instance.request(config)
  }
}

export default Request
